package com.webproject.core.config;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.webproject.core.base.BaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器 token拦截器
 * 拦截请求前参数 校验本次请求是否合法 部分需要鉴权的接口校验token有效性
 */
@Component
public class TokenHandlerInterceptor implements HandlerInterceptor {

    @Value("${jwt.key}")
    private String jwtKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证jwt token 准确性
        String token = request.getHeader("token");
        boolean verify = JWTUtil.verify(token, jwtKey.getBytes());
        if (!verify){
            // token验证不通过 抛出异常
            throw new BaseException("未登录");

        }
        // 解析jwt token 将userId和username信息提取到当前request
        JWT jwt = JWTUtil.parseToken(token);
        String userId = jwt.getPayload("userId").toString();
        String username = jwt.getPayload("username").toString();
        request.setAttribute("userId",userId);
        request.setAttribute("username",username);
        return true;
    }
}
